package org.jash.shop2202.shop

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import org.jash.shop2202.entity.CartItem
import org.jash.shop2202.mvvm.BaseViewModel
import org.jash.shop2202.net.ApiService
import org.jash.shop2202.utils.getService

class CartViewModel:BaseViewModel() {
    val service:ApiService by lazy { getService() }
    val cartItemLiveData by lazy { MutableLiveData<List<CartItem>>() }
    val deleteLiveData by lazy { MutableLiveData<String>() }
    fun loadCartItem() {
        viewModelScope.launch {
            try {
                val res = service.getCart()
                if (res.code == 200) {
                    cartItemLiveData.postValue(res.data)
                } else {
                    failureLiveData.postValue(RuntimeException(res.message))
                }
            } catch (e:Exception) {
                failureLiveData.postValue(e)
            }
        }
    }

    fun deleteCart(id:Int) {
        viewModelScope.launch {
            try {
                val res = service.deleteCart(mapOf("ids" to id))
                if (res.code == 200) {
                    deleteLiveData.postValue(res.message)
                } else {
                    failureLiveData.postValue(RuntimeException(res.message))
                }
            } catch (e:Exception) {
                failureLiveData.postValue(e)
            }
        }
    }
}